import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:image_picker/image_picker.dart';
import 'package:landlore/customWidget/addRoomTextField.dart';
import 'package:landlore/model/roomCheckInOut.dart';
import 'package:landlore/model/roomInfo.dart';
import 'package:landlore/screens/outputBillCheckInOutScreen.dart';
import 'package:syncfusion_flutter_datepicker/datepicker.dart';

import '../customWidget/recordBody.dart';
import '../dbUtil/databaseHelper.dart';
import '../model/orderVO.dart';

class RoomCheckInOutScreen extends StatefulWidget {
  final RoomInfo roomInfo;
  final int state;

  RoomCheckInOutScreen(
      {super.key, required this.roomInfo, required this.state});

  @override
  State<RoomCheckInOutScreen> createState() => _RoomCheckInOutScreenState();
}

class _RoomCheckInOutScreenState extends State<RoomCheckInOutScreen> {
  RoomInfo? roomInfo;
  double rentTemp = 0;
  double otherChargeTemp = 0;

  double deposit = 0;
  TextEditingController c1 = TextEditingController();
  TextEditingController c2 = TextEditingController();
  TextEditingController c3 = TextEditingController();
  TextEditingController c4 = TextEditingController();
  TextEditingController c5 = TextEditingController();
  TextEditingController c6 = TextEditingController();
  TextEditingController cTemp1 = TextEditingController();
  TextEditingController cTemp2 = TextEditingController();
  TextEditingController cTemp3 = TextEditingController();
  TextEditingController cTemp4 = TextEditingController();
  TextEditingController cTemp5 = TextEditingController();

  late DateTime selectedDate;

  final picker = ImagePicker();
  String? eleImgPath;
  String? waterImgPath;

  bool isRefundDeposit = true;
  bool isRefundRemain = true;

  int electricityAmountLastMonth =0;
  int waterAmountLastMonth =0;

  int electricityAmount =0;
  int waterAmount =0;
  DateTime lastMonthDate =DateTime.now();

  @override
  void initState() {
    // TODO: implement initState
    DateTime now = DateTime.now();
    selectedDate = DateTime(now.year, now.month, now.day);
    roomInfo = widget.roomInfo == null ? RoomInfo.empty() : widget.roomInfo;
    rentTemp = widget.roomInfo!.rent!;
    otherChargeTemp = widget.roomInfo!.otherCharge!;
    _getLastMonthData();
    super.initState();
  }

  _getLastMonthData() async {
    //更新获取上月抄表数据
    OrderVO lastMonthOrder = await DatabaseHelper.instance
        .getLastMonthDataByRoomId_DateTime(
        widget.roomInfo!.id!, DateTime(selectedDate.year, selectedDate.month));

    setState(() {
      lastMonthDate = lastMonthOrder.createDate!;
      electricityAmountLastMonth = lastMonthOrder.electricityAmount!;
      waterAmountLastMonth = lastMonthOrder.waterAmount!;
      //赋初值为上月数值
      electricityAmount=electricityAmountLastMonth;
      waterAmount=waterAmountLastMonth;
    });
  }

  @override
  void dispose() {
    c1.dispose();
    c2.dispose();
    c3.dispose();
    c4.dispose();
    c5.dispose();
    c6.dispose();
    cTemp1.dispose();
    cTemp2.dispose();
    cTemp3.dispose();
    cTemp4.dispose();
    cTemp5.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return MediaQuery(
      ///设置文字大小不随系统设置改变
      data: MediaQuery.of(context).copyWith(textScaleFactor: 1.0),
      child: Scaffold(
        appBar: AppBar(
          backgroundColor: const Color(0xffe9c46a),
          leading: IconButton(
            icon: Icon(
              Icons.arrow_back_ios,
              size: 35.sp,
              color: Colors.black,
            ),
            onPressed: () => Navigator.pop(context),
          ),
          title: Text(
            widget.state == 1
                ? "${roomInfo!.roomNum}入住登记"
                : "${roomInfo!.roomNum}退租登记",
            style: TextStyle(
                decoration: TextDecoration.none,
                fontSize: 35.sp,
                color: Colors.black,
                fontWeight: FontWeight.w900),
          ),
          centerTitle: true,
        ),
        body: Container(
          decoration: BoxDecoration(
              color: const Color(0xfff4a261),
              image: DecorationImage(
                  image: const AssetImage('assets/images/crossword.png'),
                  repeat: ImageRepeat.repeat,
                  colorFilter: ColorFilter.mode(
                      Colors.black.withOpacity(0.3), BlendMode.srcIn))),
          child: SingleChildScrollView(
            child: Column(
              children: [
                Card(
                  margin: EdgeInsets.only(left: 10.w, right: 10.w, top: 25.h),
                  color: Colors.white70,
                  child: Container(
                    // height: 500.h,
                    // width: 400.w,
                    padding: EdgeInsets.only(left: 10.w, bottom: 10.h),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          widget.state == 1 ? '入住日期' : '退租日期',
                          style:
                              TextStyle(color: Colors.black, fontSize: 40.sp),
                        ),
                        SfDateRangePicker(
                          view: DateRangePickerView.month,
                          initialSelectedDate: selectedDate,
                          onSelectionChanged: _onSelectionChanged,
                          selectionMode: DateRangePickerSelectionMode.single,
                        ),
                      ],
                    ),
                  ),
                ),
                Offstage(
                  offstage: widget.state == 1,
                  child: Column(
                    children: [
                      Card(
                        margin:
                            EdgeInsets.only(left: 10.w, right: 10.w, top: 25.h),
                        color: Colors.white70,
                        child: Row(
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: [
                            CupertinoCheckbox(
                                value: isRefundDeposit,
                                onChanged: (value) {
                                  setState(() {
                                    isRefundDeposit = value ?? false;
                                  });
                                }),
                            Text(
                              '退还押金',
                              style: TextStyle(fontSize: 25.sp),
                            )
                          ],
                        ),
                      ),
                      Card(
                        margin:
                            EdgeInsets.only(left: 10.w, right: 10.w, top: 25.h),
                        color: Colors.white70,
                        child: Row(
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: [
                            CupertinoCheckbox(
                                value: isRefundRemain,
                                onChanged: (value) {
                                  setState(() {
                                    isRefundRemain = value ?? false;
                                  });
                                }),
                            Text(
                              '退还当月剩余租金',
                              style: TextStyle(fontSize: 25.sp),
                            )
                          ],
                        ),
                      ),
                      Padding(
                        padding:  EdgeInsets.only(top: 20.h,left: 10.w),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.start,
                          children: [
                            Text('${lastMonthDate.year}年${lastMonthDate.month}月读数:$electricityAmountLastMonth',style: TextStyle(fontSize: 25.sp),),
                          ],
                        ),
                      ),
                      AddRoomTextField(
                          title: "电表读数",
                          value:  electricityAmount.toString(),
                          controller: cTemp4,
                          digitsOnly: true,
                          callback: (value) {
                            setState(() {
                              electricityAmount = int.parse(value);
                            });
                          }),
                      Padding(
                        padding:  EdgeInsets.only(top: 20.h,left: 10.w),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.start,
                          children: [
                            Text('${lastMonthDate.year}年${lastMonthDate.month}月读数:$waterAmountLastMonth',style: TextStyle(fontSize: 25.sp),),
                          ],
                        ),
                      ),
                      AddRoomTextField(
                          title: "水表读数",
                          value: waterAmount.toString(),
                          controller: cTemp5,
                          digitsOnly: true,
                          callback: (value) {
                            setState(() {
                              waterAmount = int.parse(value);
                            });
                          })
                    ],
                  ),
                ),
                Offstage(
                  offstage: widget.state == 0,
                  child: Column(
                    children: [
                      AddRoomTextField(
                          title: "联系人(选填)",
                          value: roomInfo?.contact,
                          controller: cTemp2,
                          digitsOnly: false,
                          callback: (value) {
                            value ?? '';
                            roomInfo?.contact = value;
                          }),
                      AddRoomTextField(
                          title: "电话(选填)",
                          value: roomInfo?.phone,
                          //电话可以为空
                          controller: cTemp3,
                          digitsOnly: true,
                          callback: (value) {
                            value ?? '';
                            roomInfo?.phone = value;
                          }),
                      AddRoomTextField(
                          title: "地址(选填)",
                          value: roomInfo?.address,
                          //地址可以为空
                          controller: cTemp1,
                          digitsOnly: false,
                          callback: (value) {
                            value ?? '';
                            roomInfo?.address = value;
                          }),
                      AddRoomTextField(
                          title: "押金",
                          unit: "元",
                          value: deposit.toStringAsFixed(0),
                          controller: c1,
                          digitsOnly: true,
                          callback: (value) {
                            deposit = double.tryParse(value) ?? 0.0;
                          }),
                      AddRoomTextField(
                          title: "租金",
                          unit: "元",
                          value: roomInfo?.rent != null
                              ? roomInfo?.rent!.toStringAsFixed(0)
                              : null,
                          controller: c2,
                          digitsOnly: true,
                          callback: (value) {
                            roomInfo?.rent = double.tryParse(value) ?? 0.0;
                          }),
                      AddRoomTextField(
                          title: "附加费",
                          unit: "元",
                          controller: c3,
                          digitsOnly: true,
                          value: roomInfo?.otherCharge != null
                              ? roomInfo?.otherCharge!.toStringAsFixed(1)
                              : null,
                          callback: (value) {
                            roomInfo?.otherCharge =
                                double.tryParse(value) ?? 0.0;
                          }),
                      AddRoomTextField(
                          title: "电费标准",
                          unit: "元/度",
                          controller: c4,
                          digitsOnly: true,
                          value: roomInfo?.electricityCharge != null
                              ? roomInfo?.electricityCharge!.toStringAsFixed(1)
                              : null,
                          callback: (value) {
                            roomInfo?.electricityCharge =
                                double.tryParse(value) ?? 0.0;
                          }),
                      AddRoomTextField(
                        title: "水费标准",
                        unit: "元/吨",
                        controller: c5,
                        digitsOnly: true,
                        value: roomInfo?.waterCharge != null
                            ? roomInfo?.waterCharge!.toStringAsFixed(1)
                            : null,
                        callback: (value) {
                          roomInfo?.waterCharge = double.tryParse(value) ?? 0.0;
                        },
                      ),
                    ],
                  ),
                ),
                Padding(
                  padding: EdgeInsets.all(10.h),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      cameraButton(
                        picker: picker,
                        callback: (String path) {
                          setState(() {
                            eleImgPath = path;
                          });
                        },
                        title: '初始电表存照',
                      ),
                      SizedBox(
                        width: 20.w,
                      ),
                      eleImgPath != null
                          ? GestureDetector(
                              onTap: () async {
                                await Navigator.push(
                                    context,
                                    MaterialPageRoute(
                                        builder: (context) => FullScreenImage(
                                            imagePath: eleImgPath!)));
                              },
                              child: Hero(
                                  tag: '$eleImgPath',
                                  child: Stack(
                                    clipBehavior: Clip.none,
                                    children: [
                                      ClipRRect(
                                        borderRadius:
                                            BorderRadius.circular(15.r),
                                        child: Image.file(
                                          File(eleImgPath!),
                                          width: 80.w,
                                          height: 80.w,
                                          fit: BoxFit.cover,
                                        ),
                                      ),
                                      Positioned(
                                          right: -5.w,
                                          top: -5.w,
                                          child: GestureDetector(
                                            onTap: () {
                                              setState(() {
                                                eleImgPath = null;
                                              });
                                            },
                                            child: Container(
                                                alignment: Alignment.center,
                                                width: 26.w,
                                                height: 26.w,
                                                decoration: BoxDecoration(
                                                  color: Colors.redAccent,
                                                  borderRadius:
                                                      BorderRadius.all(
                                                          Radius.circular(
                                                              20.r)),
                                                ),
                                                child: Center(
                                                    child: Text(
                                                  '×',
                                                  style: TextStyle(
                                                      fontSize: 20.sp,
                                                      fontWeight:
                                                          FontWeight.w900,
                                                      color: Colors.white),
                                                ))
                                                // Icon(Icons.close,color: Colors.black,size: 25.sp,),
                                                ),
                                          ))
                                    ],
                                  )),
                            )
                          : SizedBox(
                              height: 80.w,
                              width: 80.w,
                            ),
                    ],
                  ),
                ),
                Padding(
                  padding: EdgeInsets.all(10.h),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      cameraButton(
                        picker: picker,
                        callback: (String path) {
                          setState(() {
                            waterImgPath = path;
                          });
                        },
                        title: '初始水表存照',
                      ),
                      SizedBox(
                        width: 20.w,
                      ),
                      waterImgPath != null
                          ? GestureDetector(
                              onTap: () async {
                                await Navigator.push(
                                    context,
                                    MaterialPageRoute(
                                        builder: (context) => FullScreenImage(
                                            imagePath: waterImgPath!)));
                              },
                              child: Hero(
                                  tag: '$waterImgPath',
                                  child: Stack(
                                    clipBehavior: Clip.none,
                                    children: [
                                      ClipRRect(
                                        borderRadius:
                                            BorderRadius.circular(15.r),
                                        child: Image.file(
                                          File(waterImgPath!),
                                          width: 80.w,
                                          height: 80.w,
                                          fit: BoxFit.cover,
                                        ),
                                      ),
                                      Positioned(
                                          right: -5.w,
                                          top: -5.w,
                                          child: GestureDetector(
                                            onTap: () {
                                              setState(() {
                                                waterImgPath = null;
                                              });
                                            },
                                            child: Container(
                                                alignment: Alignment.center,
                                                width: 26.w,
                                                height: 26.w,
                                                decoration: BoxDecoration(
                                                  color: Colors.redAccent,
                                                  borderRadius:
                                                      BorderRadius.all(
                                                          Radius.circular(
                                                              20.r)),
                                                ),
                                                child: Center(
                                                    child: Text(
                                                  '×',
                                                  style: TextStyle(
                                                      fontSize: 20.sp,
                                                      fontWeight:
                                                          FontWeight.w900,
                                                      color: Colors.white),
                                                ))
                                                // Icon(Icons.close,color: Colors.black,size: 25.sp,),
                                                ),
                                          ))
                                    ],
                                  )),
                            )
                          : SizedBox(
                              height: 80.w,
                              width: 80.w,
                            ),
                    ],
                  ),
                ),
                Container(
                    padding: EdgeInsets.only(left: 100.w, right: 100.w),
                    margin: EdgeInsets.only(top: 40.h, bottom: 0.h),
                    height: 60.h,
                    child: ElevatedButton(
                        onPressed: () async {
                          //检测数据
                          List fieldNames = [
                            // '房号',
                            // '地址',
                            // '联系人'
                            // ,'电话'
                            '租金',
                            '附加费',
                            '电费',
                            '水费'
                          ];
                          List<TextEditingController> controllers = [
                            // c1,
                            c2,
                            c3,
                            c4,
                            c5,
                          ];

                          for (int i = 0; i < controllers.length; i++) {
                            //检测输入内容不能为空
                            if (controllers[i].text.isEmpty) {
                              // Show a snackbar or an alert dialog to notify which field is empty
                              final snackBar = SnackBar(
                                content: Text(
                                  '${fieldNames[i]} 不能为空!',
                                  style: TextStyle(
                                      fontSize: 20.sp, color: Colors.redAccent),
                                ),
                              );
                              ScaffoldMessenger.of(context)
                                  .showSnackBar(snackBar);
                              return;
                            }
                          }

                          //
                          if (widget.state == 0) {
                            if (isRefundDeposit) {
                              DatabaseHelper db = DatabaseHelper.instance;
                              deposit = await db
                                  .getLastCheckInDepositByRoomId_DateTime(
                                      roomInfo!.id!, selectedDate);
                            } else {
                              deposit = 0;
                            }
                            if (!isRefundRemain) {
                              roomInfo!.rent = 0;
                              roomInfo!.otherCharge = 0;
                            } else {
                              roomInfo!.rent = rentTemp;
                              roomInfo!.otherCharge = otherChargeTemp;
                            }
                            //整合checkInOut数据,跳转后,由下一个页面处理保存
                            RoomCheckInOut checkInOutData =
                                RoomCheckInOut.fromRoomInfo(
                                    roomInfo!,
                                    deposit,
                                    selectedDate,
                                    widget.state,
                                    eleImgPath,
                                    waterImgPath,
                                    null,
                                  electricityAmount,
                                  electricityAmountLastMonth,
                                  waterAmount,
                                  waterAmountLastMonth
                                );
                            checkInOutData.roomNum = roomInfo!.roomNum;
                            roomInfo!.state = widget.state;
                            Navigator.push(
                                context,
                                MaterialPageRoute(
                                    builder: (context) =>
                                        OutputBillCheckInOutScreen(
                                          roomCheckInOutVO: checkInOutData,
                                          roomInfo: roomInfo!,
                                        )));
                          } else {
                            //整合checkInOut数据,跳转后,由下一个页面处理保存
                            RoomCheckInOut checkInOutData =
                                RoomCheckInOut.fromRoomInfo(
                                    roomInfo!,
                                    deposit,
                                    selectedDate,
                                    widget.state,
                                    eleImgPath,
                                    waterImgPath,
                                    null,0,0,0,0);
                            checkInOutData.roomNum = roomInfo!.roomNum;
                            roomInfo!.state = widget.state;

                            Navigator.push(
                                context,
                                MaterialPageRoute(
                                    builder: (context) =>
                                        OutputBillCheckInOutScreen(
                                          roomCheckInOutVO: checkInOutData,
                                          roomInfo: roomInfo!,
                                        )));
                          }
                        },
                        style: ButtonStyle(
                            backgroundColor:
                                MaterialStateProperty.all(Colors.blue)),
                        child: Text(
                          '下一步',
                          style: TextStyle(
                              fontSize: 35.sp, fontWeight: FontWeight.w600),
                        ))),
                SizedBox(
                  height: widget.state == 1 ? 200.h : 300.h,
                )
              ],
            ),
          ),
        ),
      ),
    );
  }

  void _onSelectionChanged(DateRangePickerSelectionChangedArgs args) {
    setState(() {
      selectedDate = args.value;
    });
    _getLastMonthData();
  }
}

class cameraButton extends StatelessWidget {
  final ImagePicker picker;
  final Function callback;
  final String title;

  const cameraButton({
    super.key,
    required this.picker,
    required this.callback,
    required this.title,
  });

  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
        style: const ButtonStyle(
            backgroundColor: MaterialStatePropertyAll(Color(0xff90e0ef))),
        onPressed: () {
          showCupertinoModalPopup(
            context: context,
            builder: (BuildContext context) {
              return CupertinoActionSheet(
                // title: Text(''),
                actions: <Widget>[
                  CupertinoActionSheetAction(
                    child: const Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Expanded(
                            child: Text(
                          '拍照',
                          style: TextStyle(color: Colors.black54),
                        )),
                        Icon(
                          Icons.camera_alt,
                          color: Colors.black54,
                        )
                      ],
                    ),
                    onPressed: () async {
                      final image = await picker.pickImage(
                          source: ImageSource.camera, imageQuality: 50);
                      if (image != null) {
                        // //裁剪,有系统bug
                        // String? path = await cropImage(image.path,context);
                        // print(path);

                        callback(image.path);
                      }
                      Navigator.of(context).pop();
                    },
                  ),
                  CupertinoActionSheetAction(
                    child: const Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Expanded(
                            child: Text(
                          '从相册获取',
                          style: TextStyle(color: Colors.black54),
                        )),
                        Icon(
                          Icons.camera,
                          color: Colors.black54,
                        )
                      ],
                    ),
                    onPressed: () async {
                      final image = await picker.pickImage(
                          source: ImageSource.gallery, imageQuality: 50);
                      if (image != null) {
                        callback(image.path);
                      }
                      Navigator.of(context).pop();
                    },
                  ),
                ],
                cancelButton: CupertinoActionSheetAction(
                  child: const Text('取消'),
                  onPressed: () {
                    Navigator.of(context).pop();
                  },
                ),
              );
            },
          );
        },
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.end,
          children: [
            Icon(
              Icons.camera_alt_outlined,
              size: 50.sp,
            ),
            Padding(
              padding: EdgeInsets.only(bottom: 5.0.h),
              child: Text(
                title,
                style: TextStyle(
                    fontSize: 20.sp,
                    color: Colors.black54,
                    fontWeight: FontWeight.w600),
              ),
            )
          ],
        ));
  }

// Future<String?> cropImage(String path,BuildContext context) async {
//   final croppedFile = await ImageCropper().cropImage(
//     sourcePath: path,
//     compressFormat: ImageCompressFormat.jpg,
//     compressQuality: 100,
//     uiSettings: [
//       AndroidUiSettings(
//           toolbarTitle: 'Cropper',
//           toolbarColor: Colors.deepOrange,
//           toolbarWidgetColor: Colors.white,
//           initAspectRatio: CropAspectRatioPreset.original,
//           lockAspectRatio: false),
//       IOSUiSettings(
//         title: 'Cropper',
//       ),
//       WebUiSettings(
//         context: context,
//         presentStyle: CropperPresentStyle.dialog,
//         boundary: const CroppieBoundary(
//           width: 520,
//           height: 520,
//         ),
//         viewPort:
//         const CroppieViewPort(width: 480, height: 480, type: 'circle'),
//         enableExif: true,
//         enableZoom: true,
//         showZoomer: true,
//       ),
//     ],
//   );
//   return croppedFile?.path;
// }
}
